import React from "react";
import styles from "./index.module.scss";
import {throttle} from 'lodash';
import {NumberSize, Resizable} from "re-resizable";

interface IResizeProps {
  resizeChartSize: ({width, height}: NumberSize) => void;
  width?: number;
  height?: number;
  scale?: number;
}

interface IResizeState {

}

export default class ResizeBox extends React.PureComponent<IResizeProps, IResizeState> {

  public resizable: any;

  constructor(props: IResizeProps) {
    super(props);
    this.resizable = null;
    this.resizeChartSize = throttle(this.resizeChartSize, 100);
  }



  componentDidMount(): void {

  }

  componentWillReceiveProps(nextProps: Readonly<IResizeProps>, nextContext: any): void {
    this.updateResizableSize({width: nextProps.width || 0, height: nextProps.height || 0})
  }

  resizeChartSize(width: number, height: number){
    this.props.resizeChartSize({width, height});
  }

  updateResizableSize({width, height}: NumberSize) {
    if (this.resizable) {
      this.resizable.updateSize({width, height});
    }
  }

  getResizeEnable() {
    return {
      right: true, bottom: true, bottomRight: true,
      top: false,
      left: false,
      topRight: false, bottomLeft: false, topLeft: false
    }
  }

  render(): React.ReactNode {
    const {width, height, scale} = this.props;

    return <div className={styles.resize_container}>
      {/*----selected模式才可以显示-------*/}
      <Resizable
        defaultSize={{width, height}}
        // resizeRatio={this.state.scale}
        scale={scale}
        enable={this.getResizeEnable()}
        className={styles.resizableBox}
        handleClasses={{
          right: styles.rightHandler,
          bottom: styles.bottomHandler,
          bottomRight: styles.bottomRightHandler,
        }}
        onResize={(event, direction, elementRef:HTMLElement, delta: NumberSize) => {
          this.resizeChartSize(elementRef.offsetWidth, elementRef.offsetHeight);
        }}
        ref={c => {
          this.resizable = c;
        }}
      >
        <div className={styles.resize}/>
        <div className={styles.resize_handle_wrapper}>
          <div className="resize-handle handle-right"/>
          <div className="resize-handle handle-bottom"/>
          <div className="resize-handle handle-rightTop"/>
          <div className="resize-handle handle-rightBottom"/>
          <div className="resize-handle handle-leftBottom"/>
        </div>
      </Resizable>
    </div>;
  }
}
